import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  List,
  ListItem,
  ListItemText,
  Chip,
  CircularProgress,
  Alert,
} from '@mui/material';
import { PromotionResourceService } from '../../../features/promotion/services/PromotionResourceService';
import { Promotion } from '../../../features/promotion/services/PromotionService';

interface ResourcePromotionsProps {
  resourceId: string;
}

// 根据促销活动的isActive和时间判断状态
const getPromotionStatus = (promotion: Promotion): 'active' | 'expired' | 'upcoming' => {
  const now = new Date();
  const startTime = new Date(promotion.startTime);
  const endTime = new Date(promotion.endTime);
  
  if (!promotion.isActive) {
    return 'expired';
  }
  
  if (now < startTime) {
    return 'upcoming';
  }
  
  if (now > endTime) {
    return 'expired';
  }
  
  return 'active';
};

const getStatusColor = (status: string) => {
  switch (status) {
    case 'active':
      return 'success';
    case 'expired':
      return 'error';
    case 'upcoming':
      return 'warning';
    default:
      return 'default';
  }
};

const getStatusText = (status: string) => {
  switch (status) {
    case 'active':
      return '进行中';
    case 'expired':
      return '已结束';
    case 'upcoming':
      return '即将开始';
    default:
      return '未知';
  }
};

const ResourcePromotions = ({ resourceId }: ResourcePromotionsProps) => {
  const [promotions, setPromotions] = useState<Promotion[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchPromotions = async () => {
      try {
        setLoading(true);
        setError(null);
        const data = await PromotionResourceService.getResourcePromotions(resourceId);
        console.log('ResourcePromotions组件获取到的促销活动:', data);
        setPromotions(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : '获取关联促销活动失败');
      } finally {
        setLoading(false);
      }
    };

    fetchPromotions();
  }, [resourceId]);

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" p={2}>
        <CircularProgress size={24} />
      </Box>
    );
  }

  if (error) {
    return (
      <Alert severity="error" sx={{ mt: 2 }}>
        {error}
      </Alert>
    );
  }
};

export default ResourcePromotions;